#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   model.py
@Time    :   2022-02-21 11:38:44
@Author  :   GuoLiuFang
@Version :   0.1
@Contact :   guoliufangking@gmail.com
@License :   (C)Copyright 2018-2022, RandomMatrix
@Desc    :   None
'''
import logging
file_handler = logging.FileHandler(filename='log.log')
stdout_handler = logging.StreamHandler()
logging.basicConfig(
    level=logging.DEBUG,
    handlers=[file_handler, stdout_handler],
    format='%(asctime)s - %(processName)s - %(name)s - %(relativeCreated)d - %(threadName)s - %(levelname)s -- %(message)s'
)

# import other libs
import torch
import torch.nn as nn
from utils import log_sum_exp
class BiLSTM_CRF(nn.Module):

    def __init__(self, vocab_size, tag_to_ix, embedding_dim, hidden_dim):
        super(BiLSTM_CRF, self).__init__()
        self.embedding_dim = embedding_dim
        self.hidden_dim = hidden_dim
        self.vocab_size = vocab_size
        self.tag_to_ix = tag_to_ix
        self.tagset_size = len(tag_to_ix)
        # vocab_size，很关键，模型用来跟外界沟通。
        self.word_embeds = nn.Embedding(vocab_size, embedding_dim)
        self.lstm = nn.LSTM(embedding_dim, hidden_dim,
                            num_layers=1, bidirectional=True)

        # Maps the output of the LSTM into tag space.
        self.hidden2tag = nn.Linear(hidden_dim * 2, self.tagset_size)

        # Matrix of transition parameters.  Entry i,j is the score of
        # transitioning *to* i *from* j.
        self.transitions = nn.Parameter(
            torch.randn(self.tagset_size, self.tagset_size))

        # These two statements enforce the constraint that we never transfer
        # to the start tag and we never transfer from the stop tag
        START_TAG = "<START>"
        STOP_TAG = "<STOP>"
        # never to start
        self.transitions.data[tag_to_ix[START_TAG], :] = -10000
        # never from stop
        self.transitions.data[:, tag_to_ix[STOP_TAG]] = -10000

    def _forward_alg(self, feats):
        # feats = [src len, batch size, tagset_size]
        # Do the forward algorithm to compute the partition function
        batch_size = feats.shape[1]
        init_alphas = torch.full((batch_size, self.tagset_size), -10000.)
        START_TAG = "<START>"
        STOP_TAG = "<STOP>"
        # START_TAG has all of the score.
        # forward 到 START_TAG的值，初始化为0
        init_alphas[:,self.tag_to_ix[START_TAG]] = 0.

        # Wrap in a variable so that we will get automatic backprop
        forward_var = init_alphas

        # Iterate through the sentence
        for feat in feats:
            # feat = [batch size, tagset_size]
            alphas_t = []  # The forward tensors at this timestep
            for next_tag in range(self.tagset_size):
                # broadcast the emission score: it is the same regardless of
                # the previous tag
                # batch size 个值，复制，tagset_size列。横向复制。
                emit_score = feat[:, next_tag].view(batch_size, -1).expand(batch_size, self.tagset_size)
                # the ith entry of trans_score is the score of transitioning to
                # next_tag from i
                # 到达next_tag的一共有self.tagset_size个值， 需要复制，batch size行。纵向复制。
                trans_score = self.transitions[next_tag].view(1, -1).expand(batch_size, -1)
                # The ith entry of next_tag_var is the value for the
                # edge (i -> next_tag) before we do log-sum-exp
                next_tag_var = forward_var + trans_score + emit_score
                # The forward variable for this tag is log-sum-exp of all the
                # scores.
                alphas_t.append(log_sum_exp(next_tag_var))
            forward_var = torch.cat(alphas_t).view(batch_size, -1)
        terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]]
        alpha = log_sum_exp(terminal_var)
        return alpha

    def _get_lstm_features(self, sentence):
        # sentence = [src len, batch size]
        # hidden = [n layers * n directions, batch size, hid dim]
        # self.word_embeds initial = [vocab_size, embedding_dim]
        # sentence = [scr len, batch size]
        embeds = self.word_embeds(sentence)
        # embeds = [src len, batch size, embedding_dim]
        # self.lstm initial [embedding_dim, hidden_dim]
        lstm_out, hidden = self.lstm(embeds)
        # lstm_out = [src len, batch size, hid dim * n directions]
        # hidden 并没有使用
        lstm_feats = self.hidden2tag(lstm_out)
        # lstm_feats = [src len, batch size, tagset_size]
        return lstm_feats

    def _score_sentence(self, feats, tags):
        # feats = [src len, batch size, tagset_size]
        # tags = [scr len, batch size]
        # Gives the score of a provided tag sequence
        START_TAG = "<START>"
        STOP_TAG = "<STOP>"
        batch_size = tags.shape[1]
        score = torch.zeros(batch_size)
        # torch.full = [1, batch size]
        tags = torch.cat([torch.full((1, batch_size), self.tag_to_ix[START_TAG], dtype=torch.long), tags])
        # tags = [1 + src len, batch size, tagset_size]
        for i, feat in enumerate(feats):
            # feat = [batch size, tagset_size]
            score = score + \
                self.transitions[tags[i + 1], tags[i]] + feat[torch.arange(batch_size), tags[i + 1]]
        score = score + self.transitions[self.tag_to_ix[STOP_TAG], tags[-1]]
        return score

    def _viterbi_decode(self, feats):
        # feats = [src len, batch size, tagset_size]
        START_TAG = "<START>"
        STOP_TAG = "<STOP>"
        backpointers = []
        batch_size = feats.shape[1]
        # Initialize the viterbi variables in log space
        init_vvars = torch.full((batch_size, self.tagset_size), -10000.)
        init_vvars[:, self.tag_to_ix[START_TAG]] = 0

        # forward_var at step i holds the viterbi variables for step i-1
        forward_var = init_vvars
        for feat in feats:
            bptrs_t = []  # holds the backpointers for this step
            viterbivars_t = []  # holds the viterbi variables for this step

            for next_tag in range(self.tagset_size):
                # next_tag_var[i] holds the viterbi variable for tag i at the
                # previous step, plus the score of transitioning
                # from tag i to next_tag.
                # We don't include the emission scores here because the max
                # does not depend on them (we add them in below)
                # 到达next_tag的全路径情况，再加上选来的最优化路径forward_var
                next_tag_var = forward_var + self.transitions[next_tag]
                # 从到达next_tag的路径中挑选一个最优的路径。
                max_score, best_tag_id = torch.max(next_tag_var, 1)
                # 到达第一个状态的best_tag_id
                bptrs_t.append(best_tag_id)
                viterbivars_t.append(max_score)
            # Now add in the emission scores, and assign forward_var to the set
            # of viterbi variables we just computed
            # 所有状态遍历完毕，update forward_var。从各个状态中，选择最大值
            # 最终组成，新的forward_var 此时，需要加上发射矩阵。
            forward_var = (torch.stack(viterbivars_t, dim=1) + feat)
            # 把这个序列，对应的全部，最优状态记录下来
            backpointers.append(torch.stack(bptrs_t, dim=1))

        # Transition to STOP_TAG
        terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]]
        path_score, best_tag_id = torch.max(terminal_var, 1)

        # Follow the back pointers to decode the best path.
        best_path = [best_tag_id]
        # 初始化为，从第11个中选取到stop的最佳元素
        for bptrs_t in reversed(backpointers):
            best_tag_id = bptrs_t[torch.arange(batch_size),best_tag_id]
            best_path.append(best_tag_id)
        # for 中的第一个元算代表，从第10个中选取到达第11个的最佳元素
        # for 中的最后一个代表，从start中选取到达第1个的最佳元素
        # Pop off the start tag (we dont want to return that to the caller)
        start = best_path.pop()
        assert torch.equal(start, torch.ones(batch_size) * self.tag_to_ix[START_TAG])  # Sanity check
        best_path.reverse()
        return path_score, best_path

    def neg_log_likelihood(self, sentence, tags):
        # first step
        # sentence = [src len, batch size]
        # tags = [src len, batch size]
        feats = self._get_lstm_features(sentence)
        # feats = [src len, batch size, tagset_size]
        forward_score = self._forward_alg(feats)
        gold_score = self._score_sentence(feats, tags)
        return forward_score - gold_score

    def forward(self, sentence):  # dont confuse this with _forward_alg above.
        # Get the emission scores from the BiLSTM
        lstm_feats = self._get_lstm_features(sentence)

        # Find the best path, given the features.
        score, tag_seq = self._viterbi_decode(lstm_feats)
        return score, tag_seq
